package com.jstyle.jclifexd.activity;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.android.gms.fitness.data.DataType;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.blesdk.model.StepModel;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.utils.CustomCountDownTimer;
import com.jstyle.jclifexd.utils.PermissionsUtil;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.Utils;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.jstyle.blesdk.cmdenum.SendCmdState.Set_EXERCISE_MODE;

/**
 * 开始锻炼前的倒计时
 */
public class CountDownActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.iv_count_time)
    ImageView ivCountTime;
    @BindView(R.id.iv_count_start)
    ImageView ivCountStart;
    private Disposable observable;
    private static final String TAG = "CountDownActivity";
    private int position;

    private AMapLocationClient aMapLocationClient;
    private boolean isMainLand;
    boolean LocationChanged = false;
    private int GPS_REQUEST_CODE=400;
    private MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_countdown);
        ButterKnife.bind(this);
        position = getIntent().getIntExtra(TrackActivity.key_ExerciseMode, 0);
        initLocation();
        mediaPlayer = MediaPlayer.create(this,R.raw.there);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(observable!=null&&!observable.isDisposed())observable.dispose();
    }
    private void startCountDown(){
        ivCountStart.setVisibility(View.GONE);
        new CustomCountDownTimer(4 * 1000, 1000, new CustomCountDownTimer.TimerTickListener() {
            @Override
            public void onTick(long millisLeft) {
                int count = (Long.valueOf(millisLeft/1000).intValue());
                int id = getResources().getIdentifier("timer_" + count, "drawable", getPackageName());
                ivCountTime.setImageResource(id);
                ivCountTime.setScaleX(0);
                ivCountTime.setScaleY(0);
                ObjectAnimator oa1 = ObjectAnimator.ofFloat(ivCountTime, "scaleX", 0, 1);
                oa1.setDuration(800);
                ObjectAnimator oa2 = ObjectAnimator.ofFloat(ivCountTime, "scaleY", 0, 1);
                oa2.setDuration(800);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(oa1, oa2);
                set.start();
                openmp3(count);
            }
            @Override
            public void onFinish() {
                this.onCancel();
                if(!isDestroyed()){
                    mediaPlayer.pause();
                    if(LocationChanged){
                        startActivity(isMainLand?TrackActivity.class:TrackGoogleActivity.class, TrackActivity.key_ExerciseMode, ExerciseMode.Mode_RUN);
                    }else{
                        Locale locale = getResources().getConfiguration().locale;
                        String country = locale.getCountry();
                        startActivity(country.toLowerCase().equals("cn")?TrackActivity.class:TrackGoogleActivity.class, TrackActivity.key_ExerciseMode, ExerciseMode.Mode_RUN);

                    }
                    finish();
                }

            }
            @Override
            public void onCancel() { }
        }) {}.start();
        StepModel stepModel = new StepModel();
        stepModel.setStepState(true);
        sendData(SendCmdState.SET_STEP_MODEL, stepModel);
    }

    private void showEnableGps() {
        new AlertDialog.Builder(this,R.style.appalertdialog).setTitle(R.string.open_gps_setting_title)
                .setMessage(R.string.open_gps_setting_content)
                //  取消选项
                .setNegativeButton(getString(R.string.access_no),null)
                //  确认选项
                .setPositiveButton(getString(R.string.access_now), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //跳转到手机原生设置页面
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent,GPS_REQUEST_CODE);
                    }
                })
                .setCancelable(false)
                .show();
    }

    @OnClick(R.id.iv_count_start)
    public void onViewClicked() {
       requestPermissions();
    }
    boolean startExercise;
    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState) {
            case Set_EXERCISE_MODE:
                //String enable=maps.get(DeviceKey.KEnable_exercise);
              //  int enableValue=Integer.valueOf(enable);
                    startExercise=false;

                ExerciseMode exerciseMode = new ExerciseMode();
                exerciseMode.setEnableStatus( ExerciseMode.Status_START);
                sendData(Set_EXERCISE_MODE, exerciseMode);
                break;
        }
    }

    private void initLocation(){
        aMapLocationClient=new AMapLocationClient(this);
        aMapLocationClient.setLocationListener(this);
        AMapLocationClientOption aMapLocationClientOption=new AMapLocationClientOption();
        aMapLocationClientOption.setOnceLocation(true);
        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        aMapLocationClient.setLocationOption(aMapLocationClientOption);
        aMapLocationClient.startLocation();
    }
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        isMainLand ="中国".equals(aMapLocation.getCountry())&&!"1852".equals((aMapLocation.getCityCode()));
        Log.i(TAG, "onLocationChanged: "+aMapLocation.getCountry());
       LocationChanged= !TextUtils.isEmpty(aMapLocation.getCountry());
    }


    private void requestPermissions() {

        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                startCountDown();
                startMode();
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {

            }
        }, Manifest.permission.ACCESS_FINE_LOCATION);



    }

    private void startMode(){
        if(!PermissionsUtil.isLocServiceEnable(this)){
            showEnableGps();
            return;
        }
        startExercise=true;
    }
    private  void openmp3(int type){
        try {
            if(mediaPlayer.isPlaying()){
                mediaPlayer.stop();
                mediaPlayer.release();
            }
            switch (type){
                case 3:
                    mediaPlayer =Utils.isZh(CountDownActivity.this) ?MediaPlayer.create(this,R.raw.there):MediaPlayer.create(this,R.raw.three_en);
                    break;
                case 2:
                    mediaPlayer = Utils.isZh(CountDownActivity.this) ?MediaPlayer.create(this,R.raw.two):MediaPlayer.create(this,R.raw.two_en);
                    break;
                case 1:
                    mediaPlayer = Utils.isZh(CountDownActivity.this) ?MediaPlayer.create(this,R.raw.one):MediaPlayer.create(this,R.raw.one_en);
                    break;
                /*case 1:
                    mediaPlayer = MediaPlayer.create(this,R.raw.go);
                    break;*/
            }
            if (!mediaPlayer.isPlaying()) { // 开始播放
                mediaPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
